<?php

namespace app\model\system;

use app\model\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 文件分组模型
 * 
 * @property int $id 主键ID
 * @property string $name 分组名称
 * @property string $description 分组描述
 * @property int $parent_id 父分组ID
 * @property int $admin_id 创建用户ID
 * @property int $sort 排序
 * @property int $status 状态：1启用 0禁用
 * @property int $create_time 创建时间
 * @property int $update_time 更新时间
 * @property int $delete_time 删除时间
 */
class FileGroup extends BaseModel
{
    use SoftDelete;

    protected $name = 'oa_file_group';
    protected $pk = 'id';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'parent_id' => 'integer',
        'admin_id' => 'integer',
        'sort' => 'integer',
        'status' => 'integer',
        'create_time' => 'timestamp',
        'update_time' => 'timestamp',
        'delete_time' => 'timestamp',
    ];

    /**
     * 关联创建用户
     */
    public function admin()
    {
        return $this->belongsTo('app\model\admin\User', 'admin_id', 'id');
    }

    /**
     * 关联父分组
     */
    public function parent()
    {
        return $this->belongsTo('app\model\system\FileGroup', 'parent_id', 'id');
    }

    /**
     * 关联子分组
     */
    public function children()
    {
        return $this->hasMany('app\model\system\FileGroup', 'parent_id', 'id');
    }

    /**
     * 关联文件
     */
    public function files()
    {
        return $this->hasMany('app\model\system\File', 'group_id', 'id');
    }

    /**
     * 获取分组树形结构
     */
    public static function getTree($parent_id = 0)
    {
        $groups = self::where('status', 1)
            ->order('sort asc, id asc')
            ->select();

        return self::buildTree($groups->toArray(), $parent_id);
    }

    /**
     * 构建树形结构
     */
    protected static function buildTree($data, $parent_id = 0)
    {
        $tree = [];
        foreach ($data as $item) {
            if ($item['parent_id'] == $parent_id) {
                $item['children'] = self::buildTree($data, $item['id']);
                $tree[] = $item;
            }
        }
        return $tree;
    }

    /**
     * 获取分组列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['admin', 'parent']);

        // 按父分组筛选
        if (isset($params['parent_id'])) {
            $query->where('parent_id', $params['parent_id']);
        }

        // 按创建用户筛选
        if (!empty($params['admin_id'])) {
            $query->where('admin_id', $params['admin_id']);
        }

        // 按状态筛选
        if (isset($params['status'])) {
            $query->where('status', $params['status']);
        }

        // 按关键词搜索
        if (!empty($params['keyword'])) {
            $query->where('name|description', 'like', '%' . $params['keyword'] . '%');
        }

        return $query->order('sort asc, id desc')->paginate($params['limit'] ?? 15);
    }

    /**
     * 获取所有子分组ID
     */
    public static function getChildIds($parent_id)
    {
        $ids = [$parent_id];
        $children = self::where('parent_id', $parent_id)->select();
        
        foreach ($children as $child) {
            $ids = array_merge($ids, self::getChildIds($child['id']));
        }
        
        return $ids;
    }

    /**
     * 创建分组
     */
    public static function createGroup($data = [])
    {
        $group = new self();
        $group->name = $data['name'];
        $group->description = $data['description'] ?? '';
        $group->parent_id = $data['parent_id'] ?? 0;
        $group->admin_id = $data['admin_id'] ?? 0;
        $group->sort = $data['sort'] ?? 0;
        $group->status = $data['status'] ?? 1;

        return $group->save();
    }

    /**
     * 更新分组
     */
    public static function updateGroup($id, $data = [])
    {
        $group = self::find($id);
        if (!$group) {
            return false;
        }

        if (isset($data['name'])) {
            $group->name = $data['name'];
        }
        if (isset($data['description'])) {
            $group->description = $data['description'];
        }
        if (isset($data['parent_id'])) {
            $group->parent_id = $data['parent_id'];
        }
        if (isset($data['sort'])) {
            $group->sort = $data['sort'];
        }
        if (isset($data['status'])) {
            $group->status = $data['status'];
        }

        return $group->save();
    }

    /**
     * 删除分组
     */
    public static function deleteGroup($id)
    {
        $group = self::find($id);
        if (!$group) {
            return false;
        }

        // 检查是否有子分组
        $childCount = self::where('parent_id', $id)->count();
        if ($childCount > 0) {
            throw new \Exception('该分组下还有子分组，无法删除');
        }

        // 检查是否有文件
        $fileCount = $group->files()->count();
        if ($fileCount > 0) {
            throw new \Exception('该分组下还有文件，无法删除');
        }

        return $group->delete();
    }

    /**
     * 获取分组选择树
     */
    public static function getSelectTree($exclude_id = 0)
    {
        $groups = self::where('status', 1)
            ->when($exclude_id > 0, function($query) use ($exclude_id) {
                // 排除指定ID及其子分组
                $exclude_ids = self::getChildIds($exclude_id);
                $query->whereNotIn('id', $exclude_ids);
            })
            ->order('sort asc, id asc')
            ->select();

        return self::buildOptions($groups->toArray());
    }

    /**
     * 构建选择选项
     */
    protected static function buildOptions($data, $parent_id = 0, $level = 0)
    {
        $options = [];
        foreach ($data as $item) {
            if ($item['parent_id'] == $parent_id) {
                $prefix = str_repeat('&nbsp;&nbsp;', $level * 2);
                $options[] = [
                    'value' => $item['id'],
                    'label' => $prefix . $item['name'],
                    'children' => self::buildOptions($data, $item['id'], $level + 1)
                ];
            }
        }
        return $options;
    }

    /**
     * 搜索器：按父分组ID
     */
    public function searchParentIdAttr($query, $value)
    {
        $query->where('parent_id', $value);
    }

    /**
     * 搜索器：按创建用户ID
     */
    public function searchAdminIdAttr($query, $value)
    {
        $query->where('admin_id', $value);
    }

    /**
     * 搜索器：按状态
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器：按关键词
     */
    public function searchKeywordAttr($query, $value)
    {
        $query->where('name|description', 'like', '%' . $value . '%');
    }
}